﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Linq;
using OctoOS;
using OctoOS.UI;
using System.Web.UI.HtmlControls;

public partial class __admin_attribute : OOSPage
{
	class PathInfo
	{
		[PathInfoMember(0)]
		internal long categoryID;

		[PathInfoMember(1)]
		internal long attrID;

        [PathInfoMember(2)]
        internal byte isCustom;
	}

	PathInfo _pathInfo;
    private int _valuesMinNumber = 7;
    private int _valuesEmptyNumber = 4;


	protected void Page_Init(object sender, EventArgs e)
	{
#warning admin
        //OOSRequest.Current.EnsureModerator();
		_pathInfo = EnablePathInfo<PathInfo>();
	}

   protected void Page_Load(object sender, EventArgs e)
   {
       if (_pathInfo.attrID == 0)
       {

           if (_pathInfo.isCustom == 0)
           {
               PageTitle = "Add Attribute";
               for (int i = 1; i < _valuesMinNumber; i++)
               {
                   FormRow formRow = new FormRow();
                   formRow.ID = "FormValue_" + i;
                   if (i == 1)
                   {
                       formRow.Label = "Values";
                   }
                   var inputText = new InputText();
                   inputText.ID = "Value_" + i;
                   inputText.MinLength = 0;
                   inputText.MaxLength = 100;
                   formRow.Controls.Add(inputText);
                   FormView.Controls.Add(formRow);
               }
           }
           else
           {
               PageTitle = "Add Custom Attribute";
           }
       }
       else
       {
           int maxValue;
           PageTitle = "Edit Attribute";

               var attribute = DataSource.ClassifiedAttributes_GetByID(
                   _pathInfo.categoryID,
                   _pathInfo.attrID,
                   out maxValue);

               if (attribute != null)
               {
                   if (!IsPostBack)
                   {
                       Title.Text = attribute.Title;
                       Description.Text = attribute.Description;
                       IsRequired.Checked = attribute.Required;
                   }
                   if (!attribute.IsCustom)
                   {
                       bool isLabeled = false;
                       foreach (var value in attribute.AttributeValues)
                       {
                           FormRow formRow = new FormRow();
                           formRow.ID = "FormValue_" + value.AttributeValue;
                           if (!isLabeled)
                           {
                               formRow.Label = "Values";
                               isLabeled = true;
                           }
                           formRow.Controls.Add(GetRowContent(value));
                           FormView.Controls.Add(formRow);
                       }

                       // add empty values
                       int valuesCnt = 0;
                       if (maxValue == 1)
                       {
                           valuesCnt = _valuesMinNumber;
                       }
                       else
                       {
                           valuesCnt = maxValue + _valuesEmptyNumber + 1;
                       }
                       for (var i = maxValue + 1; i < valuesCnt; i++)
                       {
                           FormRow formRow = new FormRow();
                           formRow.ID = "FormValue_" + i;
                           var inputText = new InputText();
                           inputText.ID = "Value_" + i;
                           inputText.MinLength = 0;
                           inputText.MaxLength = 100;
                           formRow.Controls.Add(inputText);
                           FormView.Controls.Add(formRow);
                       }
                   }
               }
               else
               {
                   throw new HttpException(404, "This Page Is Not Found");
               }
       }

       FormRow submitRow = new FormRow();
       var submitBtn = new Submit();
       submitBtn.ID = "Submit";
       submitBtn.Click += new EventHandler(submitBtn_Click);
       submitRow.Controls.Add(submitBtn);
       FormView.Controls.Add(submitRow);

       SetBreadcrumbs();
   }

   private void SetBreadcrumbs()
   {
       Category[] allCategories = new Category[] { };
       Helper.Categories.UpdateCategoryCache();
       allCategories = Helper.Categories.GetAllCategories();

       AddBreadcrumb(string.Empty, "/");
       Category parentCategory = Helper.Categories.GetParentCategory(_pathInfo.categoryID);
       Category grandParentCategory = Helper.Categories.GetGrandParentCategory(_pathInfo.categoryID);
       Category currentCategory = Helper.Categories.GetCategory(_pathInfo.categoryID);
       if (currentCategory != null)
       {
           if (grandParentCategory != null)
           {
               AddBreadcrumb(grandParentCategory.Name, Urls.Classifieds.GetCategoryEdit(grandParentCategory.ID));
           }
           if (parentCategory != null)
           {
               AddBreadcrumb(parentCategory.Name, Urls.Classifieds.GetCategoryEdit(parentCategory.ID));
           }
           if (currentCategory != null)
           {
               AddBreadcrumb(currentCategory.Name, Urls.Classifieds.GetCategoryEdit(currentCategory.ID));
           }
       }
   }

    
   private Control GetRowContent(AttributeValueEntity value)
   {
       HtmlTable table = new HtmlTable();
       var tableRow = new HtmlTableRow();
       table.Style.Add("margin-left", "0px");
       table.Style.Add("border-spacing", "0");


       var tableCellInput = new HtmlTableCell();
       tableCellInput.Style.Add("width", "100%");
       tableCellInput.Style.Add("padding", "0 8px 0 0");

       var inputText = new InputText();
       inputText.ID = "Value_" + value.AttributeValue;
       inputText.MinLength = 0;
       inputText.MaxLength = 100;
       inputText.Text = value.AttributeValueName;
       tableCellInput.Controls.Add(inputText);

       var tableCellButtons = new HtmlTableCell();
       tableCellButtons.Controls.Add(GetCellButtons(value.AttributeValue));

       tableRow.Cells.Add(tableCellInput);
       tableRow.Cells.Add(tableCellButtons);
       table.Rows.Add(tableRow);
       return table;
   }

   private Control GetCellButtons(short attributeValue)
   {
       var linkButton = new OctoOS.UI.LinkButton();
       linkButton.Icon = "oosres://themes/images/kde/16/delete.png";
       linkButton.HRef = Urls.Classifieds.GetAttributeValueDelete(_pathInfo.categoryID, _pathInfo.attrID, attributeValue);
       return linkButton;
   }



   void submitBtn_Click(object sender, EventArgs e)
   {
       if (Page.IsValid)
       {
           if (_pathInfo.isCustom == 0)
           {
               DataSource.ClassifiedAttributes_Save(
                   _pathInfo.categoryID,
                   _pathInfo.attrID,
                   Title.TrimmedText,
                   Description.TrimmedText,
                   IsRequired.Checked,
                   false,
                   GetAttributeValues());
           }
           else
           {
               DataSource.ClassifiedAttributes_Save(
                   _pathInfo.categoryID,
                   _pathInfo.attrID,
                   Title.TrimmedText,
                   Description.TrimmedText,
                   IsRequired.Checked,
                   true,
                   new AttributeValueEntity[] {});
           }

           Response.Redirect(Urls.Classifieds.GetCategoryEdit(_pathInfo.categoryID));
       }
   }

   private AttributeValueEntity[] GetAttributeValues()
   {
       List<AttributeValueEntity> values = new List<AttributeValueEntity>();

       foreach (Control formRow in FormView.Controls)
       {
           if (formRow.ID != null && formRow.ID.Contains("FormValue_"))
           {
               foreach (Control control in formRow.Controls)
                {
                    if (control is HtmlTable)
                    {
                        var r = (control as HtmlTable).Rows[0].Cells[0].Controls[0];
                        if ((r is InputText) && (r as InputText).ID.Contains("Value_"))
                        {
                            byte attrValue = Convert.ToByte(r.ID.Substring(r.ID.IndexOf("_") + 1, r.ID.Length - r.ID.IndexOf("_") - 1));
                            if ((r as InputText).TrimmedText != "")
                            {
                                values.Add(
                                    new AttributeValueEntity(
                                        _pathInfo.attrID,
                                        attrValue,
                                        (r as InputText).TrimmedText
                                        ));
                            }
                        }
                    }
                    else
                        if ((control is InputText) && control.ID.Contains("Value_"))
                        {
                            byte attrValue = Convert.ToByte(control.ID.Substring(control.ID.IndexOf("_") + 1, control.ID.Length - control.ID.IndexOf("_") - 1));
                            if ((control as InputText).TrimmedText != "")
                            {
                                values.Add(
                                    new AttributeValueEntity(
                                        _pathInfo.attrID,
                                        attrValue,
                                        (control as InputText).TrimmedText
                                        ));
                            }
                        }
               }
           }
       }

       return values.ToArray();
   }
}